import threading
from utils import log_debug

class AppState:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(AppState, cls).__new__(cls)
                # 初始化状态数据
                cls._instance.initialize()
        return cls._instance

    def initialize(self):
        # 用户信息
        self.current_user_id = None  # 默认用户ID
        self.current_user = None
        self.current_user_info = None

        # 应用模式和类别
        self.current_mode = None
        self.current_category = None

        # 练习进度
        self.practice_progress = {}
        self.current_practice_index = None

        # 考试状态
        self.exam_answers = {}
        self.exam_submitted = False

        log_debug("AppState initialized")

    def set_user(self, user):
        """设置当前用户"""
        self.current_user = user
        self.current_user_id = user.id
        self.current_user_info = user.__dict__()
        log_debug(f"User set: {self.current_user_id}")

    def reset_user(self):
        """重置用户信息"""
        self.current_user = None
        self.current_user_id = None
        self.current_user_info = None
        log_debug("User info reset")

    def update_practice_progress(self, category, progress):
        """更新练习进度"""
        self.practice_progress[category] = progress
        log_debug(f"Practice progress updated for category {category}: {progress}")

    def reset_practice_progress(self, category=None):
        """重置练习进度"""
        if category is None:
            self.practice_progress = {}
            log_debug("All practice progress reset")
        else:
            if category in self.practice_progress:
                self.practice_progress[category] = 0
                log_debug(f"Practice progress reset for category {category}")

    def clear_all_data(self, user_id):
        """清空指定用户的所有数据"""
        if self.current_user_id == user_id:
            # 重置用户相关状态
            self.practice_progress = {}
            self.current_practice_index = None
            self.exam_answers = {}
            self.exam_submitted = False
            log_debug(f"All data cleared for user {user_id}")
            return True
        return False

# 创建全局状态实例
app_state = AppState()